package com.m4399.gamecenter.wxapi

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import com.m4399.minigame.sdk.MiniSDK
import com.m4399.minigame.sdk.MiniSDK.TAG
import com.m4399.minigame.sdk.MiniSDK.accountInfo
import com.m4399.minigame.sdk.MiniSDK.startMiniById
import com.m4399.minigamedemo.MiniGameApplication
import com.m4399.minigamedemo.WxShareUtils
import com.m4399.minigamedemo.WxShareUtils.currentGameId
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

class WXEntryActivity : Activity(), IWXAPIEventHandler {
    private var wxapi: IWXAPI? = null
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        wxapi!!.handleIntent(intent, this)
        Log.d(TAG, "onNewIntent: ")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        wxapi = WXAPIFactory.createWXAPI(this, WxShareUtils.WX_APP_ID)
        wxapi!!.handleIntent(intent, this)
        Log.d(TAG, "onCreate: ")
    }

    /**
     * 微信发送请求到第三方应用时，会回调到该方法
     */
    override fun onReq(baseReq: BaseReq) {
    }

    /**
     * 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
     * app发送消息给微信，处理返回消息的回调
     */
    override fun onResp(baseResp: BaseResp) {
        Log.d(TAG, "onResp: errCode ${baseResp.errCode}")
        when (baseResp.errCode) {
            BaseResp.ErrCode.ERR_OK -> {
                Log.d(TAG, "onResp: ${baseResp.type}")
                if (baseResp.type == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
//                    MiniSDK.startMiniAfterShare(currentGameId, Bundle().apply {
//                        //启动游戏进程告知结果和来源，两者必须传递否则会抛出异常
//                        putInt("shareResult", BaseResp.ErrCode.ERR_OK)
//                        Log.d(TAG, "onResp: shareSource ${MiniGameApplication.shareSource}")
//                        putInt("shareSource",MiniGameApplication.shareSource)
//                    })
                    MiniSDK.startMiniAfterShare(currentGameId, justStart = true)
                    Handler().postDelayed({
                        Log.d(TAG, "onResp: finishAndRemoveTask")
                        finishAndRemoveTask()
                    }, 500)
                }
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
                MiniSDK.startMiniAfterShare(currentGameId, justStart = true)
                Handler().postDelayed({
                    finishAndRemoveTask()
                }, 500)
            }
        }

    }
}